from WEBTest import models
from utils.base_response import BaseResponse
from ProjectTool.WebTool.ParsingStepsRealizeWebData import ParsingStepsRealizeWebData
import json


class ParsingStepsWebData:
    def __init__(self, steps_id=None, queryset=None, driver=None,
                 driver_status=None, data_warehouse=None, steps_data=None,
                 cases_status=False):
        self.res = BaseResponse()
        self.cases_status = cases_status  # 是否从用例执行
        self.data_warehouse = data_warehouse if isinstance(data_warehouse, dict) else {}  # 数据仓库
        self.driver = driver
        self.driver_status = driver_status
        self.steps_id = steps_id
        self.steps_obj = queryset
        self.obj_key = None
        self.steps_realize_objs = None
        self.steps_realize_dict = {}  # 步骤明细数据
        self.steps_data = steps_data if steps_data else {}  # 步骤数据
        self.results = 3

    # 步骤和步骤明细解析
    def parsing(self):
        if not self.steps_obj:
            self.steps_obj = models.Steps.objects.filter(id=self.steps_id).first()
        self.steps_realize_objs = self.steps_obj.stepsrealize_set.filter(status=1).order_by('sort')
        self.steps_realize_objs.update(results=3)
        self.obj_key = self.steps_obj.obj_key

    # 获取步骤数据
    def get_steps_data(self):
        if not self.cases_status:
            steps_data = self.steps_obj.steps_data
            self.steps_data = json.loads(steps_data) if steps_data else {}

    def run(self):
        self.parsing()
        self.get_steps_data()
        self.data_warehouse[self.obj_key] = self.steps_realize_dict
        page_class_obj = None
        for steps_realize_obj in self.steps_realize_objs:  # 步骤实现明细
            obj = ParsingStepsRealizeWebData(
                steps_realize_obj=steps_realize_obj,
                data_warehouse=self.data_warehouse,
                steps_data=self.steps_data,
                steps_realize_dict=self.steps_realize_dict,
                driver=self.driver,
                driver_status=self.driver_status,
                page_class_obj=page_class_obj)
            res = obj.run()
            self.results = obj.results
            page_class_obj = obj.page_class_obj  # 页面对象
            self.driver = obj.driver  # 浏览器对象
            if res.status:
                self.res = res
                break
        if self.steps_obj:
            self.steps_obj.results = self.results
            self.steps_obj.save()
        self.res.data = self.data_warehouse
        return self.res.dict
